﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using anaii.EasyNews.Data;
using DotNetNuke.Services.Exceptions;

namespace anaii.EasyNews
{
    public partial class EditNewsControl : System.Web.UI.UserControl
    {
        #region Variables

        public bool IsInsertNew
        {
            get
            {
                bool retVal = true;
                if (ViewState["IsInsertNew"] != null && bool.TryParse(ViewState["IsInsertNew"].ToString(), out retVal))
                {
                    return retVal;
                }
                return true;
            }
            set
            {
                ViewState["IsInsertNew"] = value;
            }
        }
        public int EditNewsID
        {
            get
            {
                int retVal = -1;
                if (ViewState["EditNewsID"] != null && int.TryParse(ViewState["EditNewsID"].ToString(), out retVal))
                {
                    return retVal;
                }
                return -1;
            }
            set
            {
                ViewState["EditNewsID"] = value;
            }
        }
        public string CurrentCultureCode
        {
            get
            {
                if (ViewState["CurrentCultureCode"] != null && ViewState["CurrentCultureCode"].ToString().Length > 0)
                {
                    return ViewState["CurrentCultureCode"].ToString();
                }
                return System.Threading.Thread.CurrentThread.CurrentCulture.Name;
            }
            set
            {
                ViewState["CurrentCultureCode"] = value;
            }
        }       

        #endregion

        #region Base

        protected void Page_Load(object sender, EventArgs e)
        {
            cmdCalendar.NavigateUrl = DotNetNuke.Common.Utilities.Calendar.InvokePopupCal(txtExpiredDate);
            cmdCalendar2.NavigateUrl = DotNetNuke.Common.Utilities.Calendar.InvokePopupCal(txtDateCreated);
            cmdCalendar3.NavigateUrl = DotNetNuke.Common.Utilities.Calendar.InvokePopupCal(txtPublishDate);
            if (!IsPostBack)
            {
                BindUI(null);
                Visible = false;
            }
        }

        #endregion

        #region Private Methods

        private void BindUI(EasyNew currentNews)
        {
            if (currentNews != null && currentNews.NewsID > 0)
            {
                dnn_EasyNewsTranslation translation = currentNews.dnn_EasyNewsTranslations.FirstOrDefault(p => p.Culture == CurrentCultureCode);
                if (translation == null)
                {
                    translation = new dnn_EasyNewsTranslation();
                    translation.Culture = CurrentCultureCode;
                    translation.NewsID = currentNews.NewsID;
                    currentNews.dnn_EasyNewsTranslations.Add(translation);
                }
                txtTitle.Text = translation.Title;
                txtSmallDescription.Text = translation.ShortDescription;
                (txtDescription1 as DotNetNuke.UI.UserControls.TextEditor).Text = translation.FullDescription1;
                (txtDescription2 as DotNetNuke.UI.UserControls.TextEditor).Text = translation.FullDescription2;
                (urlImage as DotNetNuke.UI.UserControls.UrlControl).Url = currentNews.ImageURL;
                (urlThumb as DotNetNuke.UI.UserControls.UrlControl).Url = currentNews.ThumbURL;
                (urlFile as DotNetNuke.UI.UserControls.UrlControl).Url = currentNews.FileURL;
                txtExternalURL.Text = currentNews.ExternalURL;
                ddlType.SelectedValue = currentNews.TypeID.ToString();
                rblStatus.SelectedIndex = (!currentNews.IsArchived) ? 0 : 1;
                txtExpiredDate.Text = (currentNews.ExpireDate.HasValue) ? currentNews.ExpireDate.Value.ToShortDateString() : "";
                txtPublishDate.Text = (currentNews.DatePublished.HasValue) ? currentNews.DatePublished.Value.ToShortDateString() : "";
                txtPublishTime.Text = (currentNews.DatePublished.HasValue) ? currentNews.DatePublished.Value.ToString("HH:mm") : "";
                txtDateCreated.Text = currentNews.DateCreated.ToShortDateString();
                cbEnabled.Checked = currentNews.IsEnabled;
            }
            else
            {
                if (this.Visible == false)
                    Clear(true);
                else
                    Clear(false);
            }
        }

        private void BindEntity(EasyNew currentNews)
        {
            dnn_EasyNewsTranslation translation = new dnn_EasyNewsTranslation();
            if (currentNews.dnn_EasyNewsTranslations == null || currentNews.dnn_EasyNewsTranslations.Count == 0 || currentNews.dnn_EasyNewsTranslations.FirstOrDefault(p => p.Culture == CurrentCultureCode) == null)
            {
                translation.Culture = CurrentCultureCode;
                translation.NewsID = currentNews.NewsID;
                currentNews.dnn_EasyNewsTranslations.Add(translation);
            }
            else
            {
                translation = currentNews.dnn_EasyNewsTranslations.FirstOrDefault(p => p.Culture == CurrentCultureCode);
            }

            translation.Title = txtTitle.Text;
            translation.ShortDescription = txtSmallDescription.Text;
            translation.FullDescription1 = (txtDescription1 as DotNetNuke.UI.UserControls.TextEditor).Text;
            translation.FullDescription2 = (txtDescription2 as DotNetNuke.UI.UserControls.TextEditor).Text;
            currentNews.ImageURL = (urlImage as DotNetNuke.UI.UserControls.UrlControl).Url;
            currentNews.ThumbURL = (urlThumb as DotNetNuke.UI.UserControls.UrlControl).Url;
            currentNews.FileURL = (urlFile as DotNetNuke.UI.UserControls.UrlControl).Url;
            currentNews.ExternalURL = txtExternalURL.Text;
            currentNews.TypeID = int.Parse(ddlType.SelectedValue);
            currentNews.IsArchived = (rblStatus.SelectedIndex == 0) ? false : true;
            currentNews.IsPublished = (rblStatus.SelectedIndex == 0) ? true : false;
            DateTime dtDate;
            if (DateTime.TryParse(txtExpiredDate.Text, out dtDate))
                currentNews.ExpireDate = dtDate;
            else
                currentNews.ExpireDate = null;
            DateTime dtCreatedDate;
            if (DateTime.TryParse(txtDateCreated.Text, out dtCreatedDate))
                currentNews.DateCreated = dtCreatedDate;
            else
                currentNews.DateCreated = DateTime.Now;
            DateTime dtPublishDate;
            if (DateTime.TryParse(txtPublishDate.Text + " " + txtPublishTime.Text, out dtPublishDate))
                currentNews.DatePublished = dtPublishDate;                
            else
                currentNews.DatePublished = null;
            currentNews.IsEnabled = cbEnabled.Checked;
        }

        #endregion

        #region Public Methods

        public bool Save(int userid)
        {
            bool retVal = false;
            Page.Validate();
            if (Page.IsValid)
            {
                EasyNews.Data.EasyNewsDBDataContext db = new anaii.EasyNews.Data.EasyNewsDBDataContext();
                EasyNew currentFund = new EasyNew();
                if (IsInsertNew)
                {
                    try
                    {
                        currentFund.CreatedBy = userid;
                        currentFund.DateCreated = DateTime.Now;
                        BindEntity(currentFund);
                        db.EasyNews.InsertOnSubmit(currentFund);
                        db.SubmitChanges();
                        retVal = true;
                    }
                    catch (Exception ex)
                    {
                        Exceptions.LogException(ex);
                        return false;
                    }
                }
                else
                {
                    currentFund = db.EasyNews.First(p => p.NewsID == EditNewsID);
                    if (currentFund != null)
                    {
                        try
                        {
                            BindEntity(currentFund);
                            db.SubmitChanges();
                            retVal = true;
                        }
                        catch (Exception ex)
                        {

                            Exceptions.LogException(ex);
                            return false;
                        }
                    }
                }

            }
            return retVal;
        }

        public void Clear(bool hide)
        {
            this.Visible = !hide;
            txtTitle.Text = "";
            txtSmallDescription.Text ="";
            (txtDescription1 as DotNetNuke.UI.UserControls.TextEditor).Text = " ";
            (txtDescription2 as DotNetNuke.UI.UserControls.TextEditor).Text = " ";
            (txtDescription1 as DotNetNuke.UI.UserControls.TextEditor).Text = "";
            (txtDescription2 as DotNetNuke.UI.UserControls.TextEditor).Text = "";
            (urlImage as DotNetNuke.UI.UserControls.UrlControl).Url = "";
            (urlThumb as DotNetNuke.UI.UserControls.UrlControl).Url = "";
            (urlFile as DotNetNuke.UI.UserControls.UrlControl).Url = "";
            txtExternalURL.Text = "";
            //ddlType.SelectedIndex = 0;
            rblStatus.SelectedIndex =  0 ;
            txtExpiredDate.Text = "";
            txtPublishDate.Text = "";
            txtPublishTime.Text = "";
            txtDateCreated.Text = DateTime.Now.ToShortDateString();
            cbEnabled.Checked = true;
            LinqDataSource1.DataBind();
            ddlType.DataBind();
        }

        public void RebindCulture(string Culture)
        {
            CurrentCultureCode = Culture;
            EasyNews.Data.EasyNewsDBDataContext db = new anaii.EasyNews.Data.EasyNewsDBDataContext();
            EasyNew currentNews = new EasyNew();
            if (IsInsertNew)
            {
                BindUI(currentNews);
            }
            else
            {
                currentNews = db.EasyNews.First(p => p.NewsID == EditNewsID);
                if (currentNews != null)
                {
                    BindUI(currentNews);
                }
            }
        }

        public void BindData(EasyNew currentNews)
        {
            IsInsertNew = true;
            EditNewsID = -1;
            Clear(false);
            if (currentNews != null)
            {
                BindUI(currentNews);
                if (currentNews.NewsID > 0)
                {
                    IsInsertNew = false;
                    EditNewsID = currentNews.NewsID;
                }
            }
        }        

        #endregion
    }
}